package response;

import java.util.Arrays;

import protocol.CtfActionException;
import structures.Position;
import utils.Conversions;

/**
 * 
 * Represents the server response to a DROP message type (4).
 * 		Object ID
 * 			 0	Error, player has nothing to drop
 * 			 1	Flag
 * 			 2	Bombs
 * 		Row
 * 			 0	invalid location to drop (i.e. wall) 
 * 			 +	row #
 * 		Column
 * 			 0 invalid location to drop
 * 			 +	column #
 */
public class DropBody {
	public static final int LENGTH = 6;	// objectID, row, col
	
	/* Field set */
	int objectId;
	Position droppedHere;
	
	public int getObjectId() { return objectId; }
	public Position getPosition() { return droppedHere; }
	
	public DropBody( byte[] response ) throws CtfActionException {
		// partition field bytes
		byte[] objectIdInBytes 	= Arrays.copyOfRange(response, 0, 2);
		byte[] rowInBytes 		= Arrays.copyOfRange(response, 2, 4);
		byte[] colInBytes 		= Arrays.copyOfRange(response, 4, 6);
		
		// convert to int
		objectId 	= Conversions.bytesToInt(objectIdInBytes);
		if ( objectId == -1 )
			throw new CtfActionException("4:drop");
		int row 	= Conversions.bytesToInt(rowInBytes);
		int col 	= Conversions.bytesToInt(colInBytes);
		droppedHere = new Position( row, col );
	}
	
	/**
	 * Set objectId, position fields. (Possible Client request usage)
	 */
	public DropBody( int objectId, Position pos ) {
		this.objectId = objectId;
		this.droppedHere = pos;
	}
	
	/**
	 * Converts the DROP body into a byte array in network byte order.
	 * @return byte array
	 */
	public byte[] toNetworkByteArray() {
		byte[] dropBodyInBytes = new byte[LENGTH];
		
		// convert fields to byte arrays
		byte[] objectIdInBytes 	= Conversions.intToBytes( objectId );
		byte[] rowInBytes 		= Conversions.intToBytes( droppedHere.row );
		byte[] colInBytes 		= Conversions.intToBytes( droppedHere.col );
		
		// concatenate field byte arrays
		System.arraycopy(objectIdInBytes, 	0, dropBodyInBytes, 0, 2);
		System.arraycopy(rowInBytes, 		0, dropBodyInBytes, 2, 2);
		System.arraycopy(colInBytes, 		0, dropBodyInBytes, 4, 2);
		
		return dropBodyInBytes;
	}
}
